package com.leetcode;

import com.leetcode.common.ListNode;

import java.util.HashMap;
import java.util.Map;

/**
 * 82. 删除排序链表中的重复元素 II
 *
 * @author fy
 * @date 2022/3/24 20:35
 */
public class Solution82 {

    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummyHead = new ListNode(-101, head);
        ListNode cur = dummyHead;
        while (cur.next != null && cur.next.next != null) {
            if (cur.next.val == cur.next.next.val) {
                int val = cur.next.val;
                while (cur.next != null && cur.next.val == val) {
                    cur.next = cur.next.next;
                }
            } else {
                cur = cur.next;
            }
        }
        return dummyHead.next;
    }

    /**
     * 使用HashMap
     *
     * @param head
     * @return
     */
    public ListNode deleteDuplicates1(ListNode head) {
        ListNode dummyHead = new ListNode(0, head);
        ListNode cur = dummyHead;
        Map<Integer, Integer> map = new HashMap<>();
        while (cur.next != null) {
            int val = cur.next.val;
            map.put(val, map.getOrDefault(val, 0) + 1);
            cur = cur.next;
        }
        cur = dummyHead;
        while (cur.next != null) {
            int val = cur.next.val;
            if (map.get(val) > 1) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return dummyHead.next;
    }

}
